<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>org-db v3 Server</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            overflow: hidden;
        }

        header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 40px;
            text-align: center;
        }

        header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        header p {
            font-size: 1.2em;
            opacity: 0.9;
        }

        .status {
            display: inline-block;
            padding: 5px 15px;
            background: #10b981;
            color: white;
            border-radius: 20px;
            font-size: 0.9em;
            margin-top: 10px;
        }

        .stop-button {
            display: inline-block;
            padding: 10px 20px;
            background: #ef4444;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 0.9em;
            margin-top: 15px;
            cursor: pointer;
            font-weight: bold;
            transition: background 0.3s;
        }

        .stop-button:hover {
            background: #dc2626;
        }

        .stop-button:disabled {
            background: #9ca3af;
            cursor: not-allowed;
        }

        .content {
            padding: 40px;
        }

        .section {
            margin-bottom: 40px;
        }

        .section h2 {
            color: #667eea;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #e5e7eb;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .stat-card {
            background: #f9fafb;
            padding: 20px;
            border-radius: 8px;
            border-left: 4px solid #667eea;
        }

        .stat-card h3 {
            color: #6b7280;
            font-size: 0.9em;
            margin-bottom: 5px;
            text-transform: uppercase;
        }

        .stat-card .value {
            font-size: 2em;
            font-weight: bold;
            color: #667eea;
        }

        .endpoint {
            background: #f9fafb;
            padding: 15px;
            margin: 10px 0;
            border-radius: 5px;
            border-left: 4px solid #764ba2;
        }

        .endpoint .method {
            display: inline-block;
            padding: 3px 8px;
            background: #667eea;
            color: white;
            border-radius: 3px;
            font-size: 0.8em;
            font-weight: bold;
            margin-right: 10px;
        }

        .endpoint .method.post {
            background: #10b981;
        }

        .endpoint .method.delete {
            background: #ef4444;
        }

        .endpoint .path {
            font-family: monospace;
            color: #374151;
        }

        .endpoint .description {
            color: #6b7280;
            margin-top: 5px;
            font-size: 0.9em;
        }

        .recent-files {
            list-style: none;
        }

        .recent-files li {
            padding: 10px;
            border-bottom: 1px solid #e5e7eb;
        }

        .recent-files li:last-child {
            border-bottom: none;
        }

        .recent-files .filename {
            font-family: monospace;
            color: #667eea;
        }

        .recent-files .time {
            color: #6b7280;
            font-size: 0.9em;
            float: right;
        }

        .features {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
        }

        .feature-card {
            background: #f9fafb;
            padding: 20px;
            border-radius: 8px;
        }

        .feature-card h3 {
            color: #667eea;
            margin-bottom: 10px;
        }

        .feature-card ul {
            margin-left: 20px;
            color: #6b7280;
        }

        footer {
            background: #f9fafb;
            padding: 20px;
            text-align: center;
            color: #6b7280;
            font-size: 0.9em;
        }

        code {
            background: #e5e7eb;
            padding: 2px 6px;
            border-radius: 3px;
            font-family: monospace;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>org-db v3</h1>
            <p>Semantic Search & Indexing for Org-Mode</p>
            <div class="status" id="status">Server Running</div>
            <br>
            <button class="stop-button" id="stop-button" onclick="stopServer()">⏹ Stop Server</button>
        </header>

        <div class="content">
            <!-- Database Information Section -->
            <div class="section">
                <h2>💾 Database Architecture</h2>
                <p style="color: #6b7280; margin-bottom: 20px;">
                    org-db v3 uses a multi-database architecture for better performance and manageability.
                    Data is separated into three specialized databases:
                </p>

                <div class="stats-grid" style="grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));">
                    <div class="stat-card" style="border-left-color: #667eea;">
                        <h3>📋 Main Database</h3>
                        <div style="font-family: monospace; color: #374151; font-size: 0.85em; margin: 10px 0;" id="main-db-location">
                            Loading...
                        </div>
                        <div class="value" id="main-db-size">-</div>
                        <p style="color: #6b7280; margin-top: 10px; font-size: 0.85em;">
                            Metadata, headlines, links, properties, tags, FTS5 full-text search index
                        </p>
                    </div>

                    <div class="stat-card" style="border-left-color: #10b981;">
                        <h3>🔍 Semantic Database</h3>
                        <div style="font-family: monospace; color: #374151; font-size: 0.85em; margin: 10px 0;" id="semantic-db-location">
                            Loading...
                        </div>
                        <div class="value" id="semantic-db-size">-</div>
                        <p style="color: #6b7280; margin-top: 10px; font-size: 0.85em;">
                            Text chunks and embeddings with libsql vector search for semantic similarity
                        </p>
                    </div>

                    <div class="stat-card" style="border-left-color: #f59e0b;">
                        <h3>🖼️ Image Database</h3>
                        <div style="font-family: monospace; color: #374151; font-size: 0.85em; margin: 10px 0;" id="image-db-location">
                            Loading...
                        </div>
                        <div class="value" id="image-db-size">-</div>
                        <p style="color: #6b7280; margin-top: 10px; font-size: 0.85em;">
                            Images and CLIP embeddings with libsql vector search for image-text matching
                        </p>
                    </div>
                </div>

                <div class="stat-card" style="background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%); border-left-color: #764ba2; margin-top: 20px;">
                    <h3>📊 Total Database Size</h3>
                    <div class="value" style="color: #764ba2;" id="total-db-size">-</div>
                    <p style="color: #6b7280; margin-top: 10px; font-size: 0.85em;">
                        Combined size of all three databases. Separation enables efficient querying and independent optimization.
                    </p>
                </div>
            </div>

            <!-- Statistics Section -->
            <div class="section">
                <h2>📊 Statistics</h2>
                <div class="stats-grid" id="stats-grid">
                    <div class="stat-card">
                        <h3>Loading...</h3>
                        <div class="value">-</div>
                    </div>
                </div>
            </div>

            <!-- Recent Files Section -->
            <div class="section">
                <h2>📁 Recent Files</h2>
                <ul class="recent-files" id="recent-files">
                    <li>Loading...</li>
                </ul>
            </div>

            <!-- Features Section -->
            <div class="section">
                <h2>✨ Features</h2>
                <div class="features">
                    <div class="feature-card">
                        <h3>🔍 Semantic Search</h3>
                        <ul>
                            <li>Find content by meaning using embeddings</li>
                            <li>Sentence transformers (all-MiniLM-L6-v2)</li>
                            <li>libsql vector search with vector_top_k()</li>
                            <li>Stored in dedicated semantic database</li>
                        </ul>
                    </div>

                    <div class="feature-card">
                        <h3>📝 Full-Text Search</h3>
                        <ul>
                            <li>Fast keyword search with SQLite FTS5</li>
                            <li>Search headlines, content, and tags</li>
                            <li>BM25 relevance ranking</li>
                            <li>Contextual snippets with highlighting</li>
                        </ul>
                    </div>

                    <div class="feature-card">
                        <h3>🖼️ Image Search</h3>
                        <ul>
                            <li>Search images by text description</li>
                            <li>CLIP (ViT-B/32) embeddings</li>
                            <li>libsql vector search for images</li>
                            <li>Stored in dedicated image database</li>
                        </ul>
                    </div>

                    <div class="feature-card">
                        <h3>⚡ Multi-Database Architecture</h3>
                        <ul>
                            <li>Separated databases for better performance</li>
                            <li>Independent optimization (ANALYZE)</li>
                            <li>Smaller individual databases</li>
                            <li>Faster vector searches (smaller indexes)</li>
                        </ul>
                    </div>
                </div>
            </div>

            <!-- API Documentation Section -->
            <div class="section">
                <h2>🔌 API Endpoints</h2>

                <div class="endpoint">
                    <span class="method">GET</span>
                    <span class="path">/health</span>
                    <div class="description">Server health check - returns status and uptime</div>
                </div>

                <div class="endpoint">
                    <span class="method post">POST</span>
                    <span class="path">/api/file</span>
                    <div class="description">
                        Index an org file - accepts JSON with filename, md5, file_size, headlines, links, keywords, src_blocks, and images.
                        Automatically generates embeddings and stores in database.
                    </div>
                </div>

                <div class="endpoint">
                    <span class="method post">POST</span>
                    <span class="path">/api/search/semantic</span>
                    <div class="description">
                        Semantic search by meaning - accepts <code>query</code> (string), <code>limit</code> (int, default 10),
                        and optional <code>model</code>. Returns ranked results with similarity scores, filenames, and line numbers.
                    </div>
                </div>

                <div class="endpoint">
                    <span class="method post">POST</span>
                    <span class="path">/api/search/fulltext</span>
                    <div class="description">
                        Full-text keyword search using SQLite FTS5 - accepts <code>query</code> (string) and <code>limit</code> (int, default 10).
                        Returns matching content with snippets and character positions.
                    </div>
                </div>

                <div class="endpoint">
                    <span class="method post">POST</span>
                    <span class="path">/api/search/images</span>
                    <div class="description">
                        Search images by text description using CLIP embeddings - accepts <code>query</code> (string) and <code>limit</code> (int, default 10).
                        Returns images with similarity scores and file locations.
                    </div>
                </div>

                <div class="endpoint">
                    <span class="method post">POST</span>
                    <span class="path">/api/search/headlines</span>
                    <div class="description">
                        Search org headlines - accepts <code>query</code> (string) and <code>limit</code> (int, default 10).
                        Returns matching headlines with their full paths and metadata.
                    </div>
                </div>

                <div class="endpoint">
                    <span class="method">GET</span>
                    <span class="path">/api/stats/</span>
                    <div class="description">Get comprehensive database statistics including file counts, embeddings, links, and database size</div>
                </div>

                <div class="endpoint">
                    <span class="method">GET</span>
                    <span class="path">/api/stats/files</span>
                    <div class="description">Get list of all indexed files with timestamps</div>
                </div>

                <div class="endpoint">
                    <span class="method delete">DELETE</span>
                    <span class="path">/api/file?filename=/path/to/file.org</span>
                    <div class="description">Remove a file and all its associated data from the database</div>
                </div>

                <div class="endpoint">
                    <span class="method post">POST</span>
                    <span class="path">/api/agenda</span>
                    <div class="description">
                        Get agenda items (TODOs, deadlines, scheduled) - accepts <code>days_ahead</code> (int, default 7).
                        Returns TODO items with their deadlines and scheduled dates.
                    </div>
                </div>

                <div class="endpoint">
                    <span class="method">GET</span>
                    <span class="path">/docs</span>
                    <div class="description">Interactive API documentation with Swagger UI - test endpoints directly in your browser</div>
                </div>
            </div>

            <!-- Getting Started Section -->
            <div class="section">
                <h2>🚀 Getting Started</h2>

                <h3 style="color: #667eea; margin-top: 20px; margin-bottom: 10px;">1. Quick Start from Emacs</h3>
                <p style="margin-bottom: 10px;">Open the main menu with:</p>
                <div style="background: #f9fafb; padding: 15px; border-radius: 5px; border-left: 4px solid #667eea; margin-bottom: 20px;">
                    <code>M-x org-db</code> or <code>H-v</code>
                </div>

                <h3 style="color: #667eea; margin-top: 20px; margin-bottom: 10px;">2. Search Commands</h3>
                <ul style="margin-left: 20px; line-height: 1.8;">
                    <li><code>v</code> - <strong>Semantic search</strong> - Find content by meaning using embeddings</li>
                    <li><code>k</code> - <strong>Full-text search</strong> - Traditional keyword search with FTS5</li>
                    <li><code>h</code> - <strong>Headline search</strong> - Browse and jump to org headlines</li>
                    <li><code>i</code> - <strong>Image search</strong> - Find images by text description (CLIP)</li>
                    <li><code>p</code> - <strong>Search at point</strong> - Search using selected text or sentence at point</li>
                </ul>

                <h3 style="color: #667eea; margin-top: 20px; margin-bottom: 10px;">3. Indexing Commands</h3>
                <ul style="margin-left: 20px; line-height: 1.8;">
                    <li><code>u</code> - Update current file</li>
                    <li><code>U</code> - Update all open org buffers</li>
                    <li><code>d</code> - Index entire directory</li>
                    <li><code>r</code> - Reindex all files in database</li>
                </ul>

                <h3 style="color: #667eea; margin-top: 20px; margin-bottom: 10px;">4. Other Features</h3>
                <ul style="margin-left: 20px; line-height: 1.8;">
                    <li><code>a</code> - <strong>Agenda</strong> - View TODOs, deadlines, and scheduled items</li>
                    <li><code>f</code> - <strong>Open file</strong> - Browse and open any file in the database</li>
                    <li><code>W</code> - Open this web interface</li>
                    <li><code>L</code> - View server logs</li>
                </ul>

                <h3 style="color: #667eea; margin-top: 20px; margin-bottom: 10px;">5. First Time Setup</h3>
                <div style="background: #f9fafb; padding: 15px; border-radius: 5px; border-left: 4px solid #10b981; margin-top: 10px;">
                    <p style="margin-bottom: 10px;">Add to your Emacs config:</p>
                    <pre style="background: #e5e7eb; padding: 10px; border-radius: 3px; overflow-x: auto;"><code>(add-to-list 'load-path "/path/to/org-db-v3/elisp")
(require 'org-db-v3)

;; Bind the menu to a convenient key
(global-set-key (kbd "H-v") 'org-db-menu)

;; Auto-start server when Emacs starts (optional)
(setq org-db-v3-auto-start-server t)</code></pre>
                </div>
            </div>

            <!-- Server Logs Section -->
            <div class="section">
                <h2>📋 Recent Server Logs</h2>
                <div id="logs-container" style="background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 8px; padding: 15px; max-height: 300px; overflow-y: auto; font-family: 'Courier New', monospace; font-size: 0.85em;">
                    <div style="text-align: center; color: #6c757d; padding: 20px;">
                        Loading logs...
                    </div>
                </div>
                <p style="margin-top: 10px; color: #6c757d; font-size: 0.9em;">Showing last 10 log entries • Auto-refreshes every 10 seconds</p>
            </div>
        </div>

        <footer>
            <p>org-db v3 - Powered by FastAPI, SQLite, Sentence Transformers, and CLIP</p>
            <p style="margin-top: 5px;">
                <a href="/docs" style="color: #667eea; text-decoration: none;">API Documentation</a> |
                <a href="/health" style="color: #667eea; text-decoration: none;">Health Check</a>
            </p>
        </footer>
    </div>

    <script>
        // Fetch and display statistics
        async function loadStats() {
            try {
                const response = await fetch('/api/stats/');
                const stats = await response.json();

                // Update status
                document.getElementById('status').textContent = 'Server Running';
                document.getElementById('status').style.background = '#10b981';

                // Update database locations and sizes
                if (stats.main_db_path) {
                    document.getElementById('main-db-location').textContent = stats.main_db_path;
                    document.getElementById('main-db-size').textContent = stats.main_db_size_mb + ' MB';
                }
                if (stats.semantic_db_path) {
                    document.getElementById('semantic-db-location').textContent = stats.semantic_db_path;
                    document.getElementById('semantic-db-size').textContent = stats.semantic_db_size_mb + ' MB';
                }
                if (stats.image_db_path) {
                    document.getElementById('image-db-location').textContent = stats.image_db_path;
                    document.getElementById('image-db-size').textContent = stats.image_db_size_mb + ' MB';
                }
                if (stats.total_db_size_mb) {
                    document.getElementById('total-db-size').textContent = stats.total_db_size_mb + ' MB';
                }

                // Update stats grid
                const statsGrid = document.getElementById('stats-grid');
                statsGrid.innerHTML = `
                    <div class="stat-card">
                        <h3>Org Files Indexed</h3>
                        <div class="value">${stats.org_files_count}</div>
                    </div>
                    <div class="stat-card">
                        <h3>Other Files Indexed</h3>
                        <div class="value">${stats.linked_files_count}</div>
                        <p style="font-size: 0.75em; color: #6b7280; margin-top: 5px;">PDF, DOCX, etc.</p>
                    </div>
                    <div class="stat-card">
                        <h3>Headlines</h3>
                        <div class="value">${stats.headlines_count}</div>
                    </div>
                    <div class="stat-card">
                        <h3>Links</h3>
                        <div class="value">${stats.links_count}</div>
                    </div>
                    <div class="stat-card">
                        <h3>Text Chunks</h3>
                        <div class="value">${stats.chunks_count}</div>
                    </div>
                    <div class="stat-card">
                        <h3>Embeddings</h3>
                        <div class="value">${stats.embeddings_count}</div>
                    </div>
                    <div class="stat-card">
                        <h3>Images</h3>
                        <div class="value">${stats.images_count}</div>
                    </div>
                    <div class="stat-card">
                        <h3>FTS Entries</h3>
                        <div class="value">${stats.fts_entries_count}</div>
                    </div>
                    <div class="stat-card">
                        <h3>Database Size</h3>
                        <div class="value">${stats.db_size_mb} MB</div>
                    </div>
                `;

                // Update recent files
                const recentFiles = document.getElementById('recent-files');
                if (stats.recent_files && stats.recent_files.length > 0) {
                    recentFiles.innerHTML = stats.recent_files.map(file => `
                        <li>
                            <span class="filename">${file.filename}</span>
                            <span class="time">${new Date(file.indexed_at).toLocaleString()}</span>
                        </li>
                    `).join('');
                } else {
                    recentFiles.innerHTML = '<li>No files indexed yet</li>';
                }
            } catch (error) {
                console.error('Error loading stats:', error);
                document.getElementById('status').textContent = 'Error Loading Stats';
                document.getElementById('status').style.background = '#ef4444';
            }
        }

        // Load stats on page load
        loadStats();

        // Load server logs
        async function loadLogs() {
            try {
                const response = await fetch('/api/logs?lines=10');
                const data = await response.json();

                const logsContainer = document.getElementById('logs-container');

                if (data.logs && data.logs.length > 0) {
                    // Build log HTML
                    let html = '';
                    data.logs.forEach(log => {
                        // Color code by level
                        let levelColor = '#6c757d';
                        if (log.level === 'ERROR') levelColor = '#dc3545';
                        else if (log.level === 'WARNING') levelColor = '#ffc107';
                        else if (log.level === 'INFO') levelColor = '#0d6efd';

                        html += `<div style="margin-bottom: 8px; padding: 6px; border-left: 3px solid ${levelColor}; background: white;">`;
                        html += `<span style="color: #6c757d; font-size: 0.8em;">${log.timestamp || 'N/A'}</span> `;
                        html += `<span style="color: ${levelColor}; font-weight: bold;">[${log.level}]</span> `;
                        html += `<span style="color: #495057;">${escapeHtml(log.message)}</span>`;
                        html += `</div>`;
                    });
                    logsContainer.innerHTML = html;
                } else {
                    logsContainer.innerHTML = '<div style="text-align: center; color: #6c757d; padding: 20px;">No logs available yet</div>';
                }
            } catch (error) {
                console.error('Error loading logs:', error);
                document.getElementById('logs-container').innerHTML =
                    '<div style="text-align: center; color: #dc3545; padding: 20px;">Failed to load logs</div>';
            }
        }

        // Helper function to escape HTML
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // Initial load
        loadLogs();

        // Refresh stats every 10 seconds
        setInterval(loadStats, 10000);

        // Refresh logs every 10 seconds
        setInterval(loadLogs, 10000);

        // Stop server function
        async function stopServer() {
            const button = document.getElementById('stop-button');
            const status = document.getElementById('status');

            if (!confirm('Are you sure you want to stop the server? This will close all connections.')) {
                return;
            }

            try {
                button.disabled = true;
                button.textContent = '⏹ Stopping...';
                status.textContent = 'Shutting down...';
                status.style.background = '#f59e0b';

                const response = await fetch('/api/shutdown', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });

                if (response.ok) {
                    status.textContent = 'Server stopped';
                    status.style.background = '#6b7280';
                    button.textContent = '⏹ Stopped';

                    // Show message after delay
                    setTimeout(() => {
                        alert('Server has been stopped. You can close this window.');
                    }, 1000);
                }
            } catch (error) {
                console.error('Error stopping server:', error);
                button.textContent = '⏹ Stop Server';
                button.disabled = false;
                status.textContent = 'Server stopped (connection lost)';
                status.style.background = '#6b7280';

                setTimeout(() => {
                    alert('Server has been stopped. You can close this window.');
                }, 500);
            }
        }
    </script>
</body>
</html>
